//
//  WebViewViewController.m
//  WXDating
//
//  Created by Andrew on 2017/12/13.
//  Copyright © 2017年 Andrew. All rights reserved.
//

#import "TL_WebViewViewController.h"
#import "TL_WeakScriptMessageHandlerDelegate.h"
//#import "TL_ShareManager.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "NSObject+Observer.h"
#import "AppDelegate.h"

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface TL_WebViewViewController () <WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *WKWebView;

@property (nonatomic, strong) UIProgressView *progressView;

//返回按钮
@property (nonatomic, strong) UIButton *customBackButton;
//关闭按钮
@property (nonatomic, strong) UIButton *closeButton;

@end

@implementation TL_WebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self reloadView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Hidden_Tabbar object:@"1"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.WKWebView setNavigationDelegate:nil];
    [self.WKWebView setUIDelegate:nil];
    
    NSArray *t_arr = self.navigationController.viewControllers;
    if (t_arr.count == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Show_Tabbar object:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self setStatusBarDefaultStyle];
}

- (void)initialize
{
    if ([self.navigationController isKindOfClass:NavigationController.class] || self.navigationController == nil) {
        [self setNavigationBarTitle:self.navTitle];
        [self hiddenNavigationBarLeftButton];
        [self.navigationBar addSubview:self.customBackButton];
        [self.navigationBar addSubview:self.closeButton];
    } else {
        [self hiddenNavigationBar:YES];
        self.navigationItem.title = self.navTitle;
        self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName : BOLD_SYSTEM_FONT(15), NSForegroundColorAttributeName : RGB(57, 56, 60)};
    }
    
    [self.view addSubview:self.WKWebView];
    [self.view addSubview:self.progressView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadView) name:NSNotification_Will_ReloadWebView object:nil];
}

- (void)reloadView {

   
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //加载网页
    [self.WKWebView loadRequest:request];
}

- (void)customBackItemClicked
{
    if (self.WKWebView.goBack) {
        [self.WKWebView goBack];
    } else {
        if (self.isPresentState) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)closeItemClicked
{
    if (self.isPresentState) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"share"]) {
//        NSDictionary *dic = [TL_UtilsHelper dictionaryWithJsonString:message.body];
//        
//        NSString *title = [TL_UtilsHelper formatStringWithObject:[dic objectForKey:@"title"]];
//        NSString *desc = [TL_UtilsHelper formatStringWithObject:[dic objectForKey:@"desc"]];
//        NSString *imageUrl = [TL_UtilsHelper formatStringWithObject:[dic objectForKey:@"image"]];
//        NSString *url = [TL_UtilsHelper formatStringWithObject:[dic objectForKey:@"url"]];
        
//        [TL_ShareManager shareWithTitle:title desc:desc imageUrl:imageUrl shareUrl:url];

        return;
    }
    
    if ([message.name isEqualToString:@"webview"]) {
        NSDictionary *dict = message.body;
        if ([dict isKindOfClass:NSString.class]) {
//            dict = [TL_UtilsHelper dictionaryWithJsonString:(NSString *)dict];
        }
        
        NSString *title = [NSString stringWithFormat:@"%@", [dict objectForKey:@"title"]];
        NSString *url = [NSString stringWithFormat:@"%@", [dict objectForKey:@"url"]];
        if (kObjectIsEmpty(url)) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"链接错误，请联系客服")];
            return;
        }
        TL_WebViewViewController *vc = [[TL_WebViewViewController alloc] init];
        vc.URLString = url;
        vc.navTitle = title;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    if ([message.name isEqualToString:@"material"]) {// 页面返回
        [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification_Will_ReloadWebView object:nil];
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if ([message.name isEqualToString:@"copy"]) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSDictionary *dic = [TL_UtilsHelper dictionaryWithJsonString:message.body];
        if (![dic objectForKey:@"copy"]) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"复制失败")];
        } else {
            pasteboard.string = [dic objectForKey:@"copy"];
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"复制成功")];
        }
        return;
    }
    
    if ([message.name isEqualToString:@"upPaid"]) {
        NSDictionary *dic = [TL_UtilsHelper dictionaryWithJsonString:message.body];
        if (self.paySuccessBlock) {
            self.paySuccessBlock([dic objectForKey:@"orderId"]);
        }
    }
}

#pragma mark - WKUIDelegate

//这个是网页加载完成，导航的变化
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.WKWebView.hidden = NO;
    });
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id result, NSError *error) {
        if (!error && result) {
            NSString *title = (NSString *)result;
            self.navTitle = title;
            [self setNavigationBarTitle:self.navTitle];
        }
    }];
}

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //开始加载的时候，让加载进度条显示
    self.progressView.hidden = NO;
}

//内容返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{}

//服务器请求跳转的时候调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    [self updateNavigationItems];
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 内容加载失败时候调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
}

//跳转失败的时候调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{}

//进度条
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{}

- (void)updateNavigationItems
{
    if (self.WKWebView.canGoBack) {
        self.closeButton.hidden = NO;
    }else{
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.closeButton.hidden = YES;
    }
}

#pragma mark - 懒加载
- (UIButton *)customBackButton
{
    if (!_customBackButton) {
        UIButton *backButton = [[UIButton alloc] init];
        backButton.frame = CGRectMake(kHalfMargin, PUB_NAVBAR_OFFSET + 20, 44, 44);
        [backButton.titleLabel setFont:kMainFont];
        [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [backButton setImage:[UIImage imageNamed:@"public_back"] forState:UIControlStateNormal];
        backButton.tintColor = kBlackColor;
        [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 6, 12, 18)];
        
        [backButton addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _customBackButton = backButton;
    }
    return _customBackButton;
}

- (UIButton *)closeButton
{
    if (!_closeButton) {
        UIButton *backButton = [[UIButton alloc] init];
        backButton.frame = CGRectMake(kHalfMargin + 44, PUB_NAVBAR_OFFSET + 20, 44, 44);
        backButton.hidden = YES;
        backButton.adjustsImageWhenHighlighted = NO;
        backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [backButton setTitle:WXLocalizedString(@"关闭") forState:UIControlStateNormal];
        [backButton.titleLabel setFont:kMainFont];
        [backButton setTitleColor:kBlackColor forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(closeItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _closeButton = backButton;
    }
    return _closeButton;
}

- (WKWebView *)WKWebView
{
    if (!_WKWebView) {
        //设置网页的配置文件
        WKWebViewConfiguration *Configuration = [[WKWebViewConfiguration alloc] init];
        //允许视频播放
        Configuration.allowsAirPlayForMediaPlayback = YES;
        // 允许在线播放
        Configuration.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互，选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        Configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        //实例化对象
        Configuration.userContentController = [WKUserContentController new];
        
        //调用JS方法
        [Configuration.userContentController addScriptMessageHandler:self name:@"share"];
        [Configuration.userContentController addScriptMessageHandler:self name:@"watch"];
        [Configuration.userContentController addScriptMessageHandler:self name:@"webview"];
        [Configuration.userContentController addScriptMessageHandler:self name:@"material"];
        [Configuration.userContentController addScriptMessageHandler:self name:@"copy"];
        [Configuration.userContentController addScriptMessageHandler:self name:@"upPaid"];
        [Configuration.userContentController addScriptMessageHandler:[[TL_WeakScriptMessageHandlerDelegate alloc] initWithDelegate:self] name:@"handleGoMall"];
        
        CGFloat y = 0;
        if ([self.navigationController isKindOfClass:NavigationController.class] || self.navigationController == nil) {
            y = PUB_NAVBAR_HEIGHT;
        } else {
            y = 0;
        }
        _WKWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, SCREEN_HEIGHT - PUB_NAVBAR_HEIGHT) configuration:Configuration];
        _WKWebView.backgroundColor = kWhiteColor;
        _WKWebView.scrollView.backgroundColor = kWhiteColor;
        _WKWebView.translatesAutoresizingMaskIntoConstraints = NO;
        // 设置代理
        _WKWebView.navigationDelegate = self;
        _WKWebView.UIDelegate = self;
        
        MK_WEAK_SELF
        //kvo 添加进度监控
        [_WKWebView addObserver:NSStringFromSelector(@selector(estimatedProgress)) complete:^(WKWebView * _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
            [weakSelf.progressView setAlpha:1.0f];
            BOOL animated = obj.estimatedProgress > weakSelf.progressView.progress;
            [weakSelf.progressView setProgress:obj.estimatedProgress animated:animated];
            
            // Once complete, fade out UIProgressView
            if(obj.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [weakSelf.progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [weakSelf.progressView setProgress:0.0f animated:NO];
                }];
            }
        }];
        //开启手势触摸
        _WKWebView.allowsBackForwardNavigationGestures = YES;

        _WKWebView.hidden = YES;
    }
    return _WKWebView;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        CGFloat y = [self.navigationController isKindOfClass:NavigationController.class] ? PUB_NAVBAR_HEIGHT : 0;
        _progressView.frame = CGRectMake(0, y, self.view.bounds.size.width, 3);
        _progressView.progressTintColor = kMainColor;
        [_progressView setTrackTintColor:[UIColor clearColor]];
    }
    return _progressView;
}

- (void)dealloc {
    [_WKWebView.configuration.userContentController removeScriptMessageHandlerForName:@"handleGoMall"];
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

@end
